package com.lepu.app.fun.tool.szqx;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.config.UserConfig;
import com.app.utils.Const;
import com.app.utils.DateUtil;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.ui.wheel.WheelView;
import com.core.lib.utils.DateType;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.tool.szqx.bean.BeanToolGrow;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class GrowAddActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, AsyncRequest {
	private LinearLayout mBabyLayout;
	private TextView mBabyDateEdit;
	private TextView mDateEdit;
	private EditText mWeightEdit;
	private EditText mHeightEdit;
	private EditText mHeadEdit;
	
	private TextView mManTextView;
	private TextView mWmanTextView;
	
	private boolean mIsFirst = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		mNeedStatusBar = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tool_grow_add_activity);

		UtilityBase.setStatusBarRes(this, R.color.color_bmi, true);
		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("生长曲线");
		topbar.setTopbarBackground(R.color.color_bmi);
		topbar.setonTopbarNewLeftLayoutListener(this);

		mIsFirst = getIntent().getBooleanExtra("isFirst", true);
		
		mBabyLayout = (LinearLayout) findViewById(R.id.babyLayout);
		mBabyDateEdit = (TextView) findViewById(R.id.babydateEditText);
		
		mDateEdit = (TextView) findViewById(R.id.dateEditText);
		mWeightEdit = (EditText) findViewById(R.id.weightEditText);
		mHeightEdit = (EditText) findViewById(R.id.heightEditText);
		mHeadEdit = (EditText) findViewById(R.id.headEditText);
		mManTextView = (TextView) findViewById(R.id.yesText);
		mWmanTextView = (TextView) findViewById(R.id.noText);
        Button saveButton = (Button) findViewById(R.id.saveButton);
		
		mDateEdit.setOnClickListener(onClick);
		mBabyDateEdit.setOnClickListener(onClick);
		mManTextView.setOnClickListener(onClick);
		mWmanTextView.setOnClickListener(onClick);
		saveButton.setOnClickListener(onClick);
		
		mWeightEdit.addTextChangedListener(new CustomTextWatcher(mWeightEdit));
		mHeightEdit.addTextChangedListener(new CustomTextWatcher(mHeightEdit));
		mHeadEdit.addTextChangedListener(new CustomTextWatcher(mHeadEdit));
		
		mManTextView.setSelected(true);
		
		if(mIsFirst){
			mBabyLayout.setVisibility(View.VISIBLE);
		}else{
			mBabyLayout.setVisibility(View.GONE);
		}
	}

	//上传 data
	public void request(BeanToolGrow bean) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID",LoginUtil.getUserId());
			params.put("LoginToken",LoginUtil.getLoginToken());

			params.put("Height", bean.height);
			params.put("Weight", bean.weight);
			params.put("HeadCircumference", bean.head);
			params.put("MeasureTime", DateUtil.getStringTime(bean.time));

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post_main(Setting.getGrowSaveUrl(), map, null, this, "",false);
	}

	//上传 出生日期  性别
	public void request(String babyDate, int sex ) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			params.put("ToolID", 1);
			params.put("BabyBirthday", babyDate);
			params.put("BabyGender", sex);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post_main(Setting.getUploadYiMiaoUrl(), map, null, this,"", true, false);
	}
	
	View.OnClickListener onClick = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.dateEditText:
				showBirthDateDialog(mDateEdit,2);
				break;
			case R.id.babydateEditText:
				showBirthDateDialog(mBabyDateEdit,1);
				break;
			case R.id.yesText:
				mManTextView.setSelected(true);
				mWmanTextView.setSelected(false);
				break;
			case R.id.noText:
				mManTextView.setSelected(false);
				mWmanTextView.setSelected(true);
				break;
			case R.id.saveButton:
			      String babyDate = mBabyDateEdit.getText().toString().trim();

					String date = mDateEdit.getText().toString().trim();
					String weight = mWeightEdit.getText().toString().trim();
					String height = mHeightEdit.getText().toString().trim();
					String head = mHeadEdit.getText().toString().trim();


					
					if (TextUtils.isEmpty(date)) {
						UIHelper.showToast(GrowAddActivity.this, "请完整填写 记录日期");
						return;
					}
					if (TextUtils.isEmpty(weight) || weight.equals("0")) {
						UIHelper.showToast(GrowAddActivity.this, "请完整填写宝宝 “体重”");
						return;
					}

					if (TextUtils.isEmpty(height) || height.equals("0")) {
						UIHelper.showToast(GrowAddActivity.this, "请完整填写宝宝 “身高”");
						return;
					}
					
					if (TextUtils.isEmpty(head) || head.equals("0")) {
						UIHelper.showToast(GrowAddActivity.this, "请完整填写宝宝 “头围”");
						return;
					}
					
					
					float weightF = Float.valueOf(weight);
					float heightF = Float.valueOf(height);
					float headF = Float.valueOf(head);
					
					
					if(weightF < 0 || weightF > 40){
						UIHelper.showToast(GrowAddActivity.this, "请填写0~40kg体重");
						return;
					}
					
					if(heightF < 30 || heightF > 140){
						UIHelper.showToast(GrowAddActivity.this, "请填写30~140cm身高");
						return;
					}
					
					if(headF < 30 || headF > 60){
						UIHelper.showToast(GrowAddActivity.this, "请填写30~60cm头围");
						return;
					}

					//save first
					if(mIsFirst){
						if (TextUtils.isEmpty(babyDate)) {
							UIHelper.showToast(GrowAddActivity.this, "请完整填写 宝宝出生日期");
							return;
						}else{
							UserConfig.setConfig(GrowAddActivity.this, Const.CONFIG_APP_BABY_DATE, babyDate);
							
							int sex = 1;
							if(mManTextView.isSelected()){
								//男
								UserConfig.setConfig(GrowAddActivity.this, Const.CONFIG_APP_BABY_SEX, 1);
								sex = 1;
							}else{
								//女
								UserConfig.setConfig(GrowAddActivity.this, Const.CONFIG_APP_BABY_SEX, 2);
								sex = 2;
							}
							
							request(babyDate, sex);
						}
					}
					
					long longTime = DateUtil.getLongTime(date);
					BeanToolGrow bean = new BeanToolGrow();
					bean.uid = LoginUtil.getUserId();
					bean.type = 1;
					bean.time = longTime;
					bean.weight = weight;
					bean.height = height;
					bean.head = head;
					
					//save db
					BeanToolGrow.insert(bean);
					//刷新界面	
					ObserverManager.getInstance().notify(ObserverConst.NOTIFY_GROW_CHANGE, null, null);
					
					//save web
					request(bean);
					showProgressDialog();
					
				break;
			default:
				break;
			}
		}
	};

	private void showBirthDateDialog(final TextView textView, final int type) {

		String babyDate = UserConfig.getConfigString(GrowAddActivity.this, Const.CONFIG_APP_BABY_DATE, "");
		String dateStr = "";
		if (TextUtils.isEmpty(babyDate)) {
			dateStr = DateUtilBase.stringFromDate(new Date(),DateUtilBase.YEAR_MONTH_DAY);
		} else {
			Date date = DateUtilBase.dateFromString(babyDate,DateUtilBase.YEAR_MONTH_DAY);
			dateStr = DateUtilBase.stringFromDate(date,DateUtilBase.YEAR_MONTH_DAY);
		}

		Date date = DateUtilBase.dateFromString(dateStr,DateUtilBase.YEAR_MONTH_DAY);
		MyDialog dialog = new MyDialog(GrowAddActivity.this)
				.setTitle("请选择宝宝出生日期")
				.setDateTimePicker(date, DateType.YEAR_MONTH_DAY)
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View arg0) {

							}
						})
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// 如果是个数,则显示为"02"的样式
						WheelView wv_year = (WheelView) v
								.findViewById(R.id.year);
						WheelView wv_month = (WheelView) v
								.findViewById(R.id.month);
						WheelView wv_day = (WheelView) v.findViewById(R.id.day);

						String parten = "00";
						DecimalFormat decimal = new DecimalFormat(parten);
						// 设置日期的显示
						String text = (wv_year.getCurrentItem() + MyDialog.START_YEAR)
								+ "-"
								+ decimal.format((wv_month.getCurrentItem() + 1))
								+ "-"
								+ decimal.format((wv_day.getCurrentItem() + 1));

						//出生日期
						if(type == 1){
							if(DateUtil.getLongTime(text) > DateUtil.getLongTime(DateUtil.stringFromDate(new Date(), DateUtilBase.YEAR_MONTH_DAY))){
								UIHelper.showToast(GrowAddActivity.this, "不能选择未来时间");
							}else{
								textView.setText(text);
								UserConfig.setConfig(GrowAddActivity.this, Const.CONFIG_APP_BABY_DATE, text);
							}
						}
						//记录日期
						else if(type == 2){
							String babyDate = UserConfig.getConfigString(GrowAddActivity.this, Const.CONFIG_APP_BABY_DATE, "");
							if(DateUtil.getLongTime(text) < DateUtil.getLongTime(babyDate)){
								UIHelper.showToast(GrowAddActivity.this, "不能选择宝宝出生之前的日期");
							}else if(DateUtil.getLongTime(text) > DateUtil.getLongTime(babyDate)+ (DateUtil.YEAR_MILLIS*10)){
								UIHelper.showToast(GrowAddActivity.this, "不能选择宝宝十岁之后的日期");
							}else{
								textView.setText(text);
							}
						}
						
					}
				});

		dialog.create(null).show();
	}
	
//	private void showBirthDateDialog(final TextView textView) {
//
//		String babyDate = UserConfig.getConfigString(GrowAddActivity.this, Const.CONFIG_APP_BABY_DATE, "");
//		String dateStr = DateUtilBase.stringFromDate(new Date(),DateUtilBase.DATE_ALL);
//		if (TextUtils.isEmpty(babyDate)) {
//			dateStr = DateUtilBase.stringFromDate(new Date(),DateUtilBase.DATE_ALL);
//		} else {
//			Date date = DateUtilBase.dateFromString(babyDate,DateUtilBase.DATE_ALL);
//			dateStr = DateUtilBase.stringFromDate(date,DateUtilBase.DATE_ALL);
//		}
//
//		Date date = DateUtilBase.dateFromString(dateStr,DateUtilBase.DATE_ALL);
//		MyDialog dialog = new MyDialog(GrowAddActivity.this)
//				.setTitle("请选择日期")
//				.setDateFullTimePicker(date)
//				.setNegativeButton(R.string.app_cancel,
//						new View.OnClickListener() {
//
//							@Override
//							public void onClick(View arg0) {
//
//							}
//						})
//				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {
//					@Override
//					public void onClick(View v) {
//						// 如果是个数,则显示为"02"的样式
//						WheelView wv_year = (WheelView) v.findViewById(R.id.yearFull);
//						WheelView wv_month = (WheelView) v.findViewById(R.id.monthFull);
//						WheelView wv_day = (WheelView) v.findViewById(R.id.dayFull);
//						WheelView wv_hour = (WheelView) v.findViewById(R.id.hourFull);
//						WheelView wv_min = (WheelView) v.findViewById(R.id.minuteFull);
//
//						String parten = "00";
//						DecimalFormat decimal = new DecimalFormat(parten);
//						// 设置日期的显示
//						String text = (wv_year.getCurrentItem() + MyDialog.START_YEAR)
//								+ "-"
//								+ decimal.format((wv_month.getCurrentItem() + 1))
//								+ "-"
//								+ decimal.format((wv_day.getCurrentItem() + 1))
//								+ " "
//								+decimal.format((wv_hour.getCurrentItem() ))
//								+ ":"
//								+decimal.format((wv_min.getCurrentItem() ));
//
//						textView.setText(text);
//
//					}
//				});
//
//		dialog.create(null).show();
//	}
	
	class CustomTextWatcher implements TextWatcher {

		EditText contentEditText;

		public CustomTextWatcher(EditText editText) {
			contentEditText = editText;
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			String content = s.toString().trim();

			if (TextUtils.isEmpty(content)) {

			} else {
				// new
				if (content.contains(".")) {
					if (s.length() - 1 - content.indexOf(".") > 2) {
						s = content.subSequence(0,
								content.indexOf(".") + 3);
						contentEditText.setText(s);
						contentEditText.setSelection(s.length());
					}
				}
				
				if (content.substring(0).equals(".")) {
					s = "0" + s;
					contentEditText.setText(s);
					contentEditText.setSelection(2);
				}

				if (content.startsWith("0")
						&& content.length() > 1) {
					if (!content.substring(1, 2).equals(".")) {
						contentEditText.setText(s.subSequence(0, 1));
						contentEditText.setSelection(1);
						return;
					}
				}
				
				//小数点前限制前3位
				int value = UtilityBase.parseInt(content);
				if(value >= 1000){
					content = content.substring(0,3);
					contentEditText.setText(content);
					contentEditText.setSelection(content.length());
				}
			}
		}

		@Override
		public void afterTextChanged(Editable s) {

		}
	}
	
	@Override
	public void RequestComplete(Object arg0, Object arg1) {
		if(mIsFirst){
			startActivity(new Intent(GrowAddActivity.this,GrowActivity.class),true);
			UserConfig.setConfig(GrowAddActivity.this, Const.CONFIG_APP_BABY_FIRST, false);
		}
		
		finish(true);
		showProgressDialog();
	}

	@Override
	public void RequestError(Object arg0, int arg1, String arg2) {
		if(mIsFirst){
			startActivity(new Intent(GrowAddActivity.this,GrowActivity.class),true);
			UserConfig.setConfig(GrowAddActivity.this, Const.CONFIG_APP_BABY_FIRST, false);
		}
		finish(true);
		showProgressDialog();
	}

}
